<template>
  <div class="popup-container" @click.stop>
    <div class="header">
      <div class="title">产业类别</div>
      <div class="dropdown-menu">
        <van-popover
          @click.stop
          class="popover-wrap"
          v-model:show="showPopover"
          :actions="industryTypeList"
          @select="changeIndustryType"
        >
          <template #reference>
            <div class="level">
              <span>{{ currentIndustryType.text }}</span>
              <img
                :src="arrowDown"
                :class="['icon', showPopover ? 'rotate' : '']"
                alt=""
              />
            </div>
          </template>
        </van-popover>
      </div>
    </div>
    <div class="list-container">
      <div class="left-column">
        <div
          :class="
            firstCategoryIndex == index
              ? 'first-category-active'
              : 'first-category'
          "
          v-for="(firstItem, index) in industryList"
          :key="index"
          @click="changeFirstCategory(index)"
        >
          {{ firstItem.industryName }}
        </div>
      </div>
      <div
        class="right-column"
        ref="rightContainer"
        @scroll="handleIndustryScroll"
      >
        <div
          class="category"
          v-for="(firstItem, index) in industryList"
          :key="index"
        >
          <div class="first-title">
            <div>{{ firstItem.industryName }}</div>
          </div>
          <div
            class="second-item"
            v-for="(secondItem, secondIndex) in firstItem.children"
            :key="secondIndex"
            @click="onToggleSecondIndustry(secondItem)"
          >
            <div
              :class="[
                'second-item-title',
                secondItem.showChildren ? 'float-title' : '',
              ]"
            >
              <img
                :class="[
                  'arrow-icon',
                  secondItem.showChildren ? 'arrow-rotate' : '',
                ]"
                src="@/assets/images/arrow_down.png"
                class="arrow-icon"
                alt=""
              />
              <span class="second-item-title-text">
                <span class="text-content">{{ secondItem.industryName }}</span>
                <text class="count-text"
                  >({{ secondItem.extendJson.num }}个)</text
                >
              </span>
              <img
                @click.stop="onSelectSecondIndustry(secondItem)"
                :src="
                  secondItem.industryId ==
                  currentSelectSecondIndustry.industryId
                    ? check
                    : uncheck
                "
                class="selected-img"
                alt=""
              />
            </div>
            <transition name="slide-fade">
              <div
                v-if="secondItem.showChildren"
                class="third-category-wrapper"
              >
                <div class="third-item-special">产业对应的专业</div>
                <div
                  class="third-item"
                  v-for="(_item, _index) in secondItem.children"
                  :key="_index"
                >
                  {{ _item.industryName }}
                </div>
              </div>
            </transition>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom-btn">
      <div
        :class="[
          'left-btn',
          currentSelectSecondIndustry?.extendJson?.num > 0 ? 'active' : '',
        ]"
        @click="clear"
      >
        清除已选类型
      </div>
      <div class="right-btn" @click="confirm">
        <span v-if="currentSelectSecondIndustry?.extendJson?.num > 0">
          已选{{ currentSelectSecondIndustry?.extendJson?.num }}个·
        </span>
        <span>确 定</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { throttle } from 'lodash-es';
import { useVolunteerStore } from '@/store/volunteer';
import check from '@/assets/images/selected.png';
import uncheck from '@/assets/images/unselected.png';
import { getIndustries, getIndustryTags } from '@/api/volunteer';
import arrowDown from '@/assets/images/arrowDown.png';

const props = defineProps({});

const store = useVolunteerStore();
const volunteerInfo = computed(() => store.volunteerInfo);
const defaultBatchType = computed(() => store.defaultBatchType);

const emit = defineEmits(['confirmIndustry', 'changeIndustryType']);

const showPopover = ref(false);

const currentIndustryType = ref({ text: '未来产业', value: 3 });

const industryTypeList = ref([
  { text: '国民经济', value: 1, className: 'popover-item' },
  { text: '工业战略新兴产业', value: 2, className: 'popover-item' },
  { text: '未来产业', value: 3, className: 'popover-item' },
]);

// 请求产业列表
const industryList = ref([]);
const getIndustriesFn = async () => {
  const params = {
    industryType: currentIndustryType.value.value,
    cpType: defaultBatchType.value, //后台根本不接受cpType参数，所以统一改成defaultBatchType 20250730
    subjectCombination: volunteerInfo.value.relSubject,
  };

  const res = await getIndustries(params);
  res.data.forEach((item) => {
    item.children.forEach((_item) => {
      _item.showChildren = false;
      _item.checked = false;
    });
  });
  industryList.value = res.data;
};

getIndustriesFn();

const changeIndustryType = (value) => {
  currentIndustryType.value = value;
  getIndustriesFn();
};

// 当前正在看的二级专业
const scrollCurrentSecondCategory = ref({});
// 添加标记变量，用于控制滚动状态
const isManualScrolling = ref(false);
// 添加防抖时间常量
const SCROLL_DEBOUNCE_TIME = 500;
// 添加滚动动画标记
const isScrolling = ref(false);
// 添加目标索引记录
const targetCategoryIndex = ref(-1);
// 左侧当前选中索引
const firstCategoryIndex = ref(0);
// 右侧容器引用
const rightContainer = ref(null);
// 当前选中的二级
const currentSelectSecondIndustry = ref({});

// 选中当前二级，单选
const onSelectSecondIndustry = (currentItem) => {
  // 如果点击的是当前选中的项，则取消选中
  if (currentSelectSecondIndustry.value.industryId === currentItem.industryId) {
    currentSelectSecondIndustry.value = {};
    currentItem.checked = false;
  } else {
    currentItem.checked = true;
    // 如果点击的是新的项，则更新选中状态
    currentSelectSecondIndustry.value = {
      ...currentItem,
    };
  }
};

// 清除已选类型
const clear = () => {
  currentSelectSecondIndustry.value = {};
  industryList.value.forEach((item) => {
    item.children.forEach((child) => {
      child.checked = false;
    });
  });
};

// 确定已选类型
const confirm = () => {
  let params = '';
  if (currentSelectSecondIndustry.value?.extendJson) {
    params = currentSelectSecondIndustry.value?.extendJson.tags || '';
  }
  emit('confirmIndustry', params);
};

// 更新二级分类显示的函数
const updateSecondCategory = (item) => {
  // 如果是手动滚动过程中，不更新状态
  if (isManualScrolling.value || isScrolling.value) return;

  if (item && item !== scrollCurrentSecondCategory.value) {
    scrollCurrentSecondCategory.value = item;
  }
};

// 重置分类状态的函数
const resetCategoryState = () => {
  // 如果是手动滚动过程中，不重置状态
  if (isManualScrolling.value || isScrolling.value) return;

  scrollCurrentSecondCategory.value = {};
  if (!isManualScrolling.value) {
    firstCategoryIndex.value = 0;
    document
      .querySelector('.left-column')
      ?.scrollTo({ top: 0, behavior: 'smooth' });
  }
};

// 获取三级专业或者显示隐藏三级专业
const onToggleSecondIndustry = async (currentItem) => {
  if (!currentItem.children) {
    const res = await getIndustryTagsFn(currentItem);
    currentItem.children = res;
  }
  currentItem.showChildren = !currentItem.showChildren;
};

// 使用节流优化滚动处理函数
const handleIndustryScroll = throttle((e) => {
  const container = e.target;

  // 如果是手动滚动过程中，只检查是否到达目标位置
  if (isManualScrolling.value || isScrolling.value) {
    if (targetCategoryIndex.value !== -1) {
      const target =
        container.querySelectorAll('.category')[targetCategoryIndex.value];
      if (target) {
        const rect = target.getBoundingClientRect();
        const containerRect = container.getBoundingClientRect();
        // 当滚动到目标位置附近时，更新状态并重置标记
        if (Math.abs(rect.top - containerRect.top) <= 50) {
          firstCategoryIndex.value = targetCategoryIndex.value;
          scrollCurrentSecondCategory.value = {};
          isManualScrolling.value = false;
          isScrolling.value = false;
          targetCategoryIndex.value = -1;
        }
      }
    }
    return;
  }

  // 当滚动到顶部时，重置状态
  if (container.scrollTop === 0) {
    resetCategoryState();
    return;
  }

  // 处理一级分类的更新
  const firstTitles = container.querySelectorAll('.first-title');
  firstTitles.forEach((title, index) => {
    const rect = title.getBoundingClientRect();
    const containerRect = container.getBoundingClientRect();

    // 当first-title到达顶部时更新状态
    if (
      rect.top - containerRect.top <= 0 &&
      rect.bottom - containerRect.top > 0
    ) {
      firstCategoryIndex.value = index;
      // 更新左侧菜单滚动位置
      const leftColumn = document.querySelector('.left-column');
      const selectedItem =
        leftColumn?.querySelectorAll('.first-category')[index];
      if (leftColumn && selectedItem) {
        const targetScrollTop =
          selectedItem.offsetTop -
          leftColumn.clientHeight / 2 +
          selectedItem.clientHeight / 2;
        leftColumn.scrollTo({ top: targetScrollTop, behavior: 'smooth' });
      }

      // 更新当前选中的二级分类
      const currentFirstItem = industryList.value[index];
      if (
        currentFirstItem &&
        currentFirstItem.children &&
        currentFirstItem.children.length > 0
      ) {
        // 找到当前可见的第一个二级分类
        const secondItems = container.querySelectorAll('.second-item');
        for (let i = 0; i < secondItems.length; i++) {
          const secondRect = secondItems[i].getBoundingClientRect();
          if (secondRect.top - containerRect.top > 0) {
            const secondItemName = secondItems[i]
              .querySelector('.second-item-title span')
              .textContent.split('(')[0];
            const currentSecondItem = currentFirstItem.children.find(
              (item) => item.name === secondItemName
            );
            if (currentSecondItem) {
              updateSecondCategory(currentSecondItem);
              break;
            }
          }
        }
      }
    }
  });
}, 100);

// 获取三级专业
const getIndustryTagsFn = async (currentItem) => {
  try {
    const params = {
      parentId: currentItem.industryId,
    };
    const res = await getIndustryTags(params);
    if (res.code == 200) {
      return res.data;
    }
  } catch (error) {
    console.log(error);
  }
};

const changeFirstCategory = async (index) => {
  // 设置滚动状态标记
  isManualScrolling.value = true;
  isScrolling.value = true;
  targetCategoryIndex.value = index;

  // 重置二级分类显示
  scrollCurrentSecondCategory.value = {};
  firstCategoryIndex.value = index;

  const target = rightContainer.value.querySelectorAll('.category')[index];
  if (!target) return;

  const containerTop = rightContainer.value.getBoundingClientRect().top;
  const targetTop = target.getBoundingClientRect().top;
  // 修改滚动位置计算，使目标位置距离顶部80px
  const scrollPosition =
    targetTop - containerTop + rightContainer.value.scrollTop;

  // 执行滚动
  rightContainer.value.scrollTo({
    top: scrollPosition,
    behavior: 'smooth',
  });

  // 设置一个较长的超时时间，确保滚动完全停止
  setTimeout(() => {
    if (isManualScrolling.value || isScrolling.value) {
      isManualScrolling.value = false;
      isScrolling.value = false;
      targetCategoryIndex.value = -1;
    }
  }, SCROLL_DEBOUNCE_TIME + 200);
};

onMounted(() => {});
</script>

<style scoped lang="scss">
.popover-wrap :deep(.van-popover__content) {
  .van-popover__action {
    width: 190px;
    color: #222;
    font-size: 18px;
  }
}
.popup-container {
  .header {
    display: flex;
    align-items: center;
    padding: 20px;
    .dropdown-menu {
      margin-left: 24px;
      .level {
        font-size: 20px;
        color: #555;
        padding: 6px 18px;
        background-color: #dff0ff;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        .icon {
          width: 16px;
          height: 16px;
          margin-left: 10px;
          transition: transform 0.3s ease;
          transform: rotate(0deg);

          &.rotate {
            transform: rotate(180deg);
          }
        }
      }
      .popover-item {
        color: red;
        background-color: #dff0ff;
      }
    }

    .title {
      font-family: PingFang-SC, PingFang-SC;
      font-weight: bold;
      font-size: 26px;
      color: #222222;
    }
  }
  .list-container {
    display: flex;
    flex-direction: row;
    height: 360px;
    position: relative;
    .left-column {
      width: 220px;
      background: #f4f6f8;
      height: 100%;
      box-sizing: border-box;
      overflow: scroll;
      border-top-right-radius: 10px; /* 右上角圆角 */
      .first-category {
        padding: 14px 6px 14px 20px;
        text-align: center;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 22px;
        color: #666666;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      .first-category-active {
        @extend .first-category;
        background: #ddeafd;
        color: $primary-color;
      }
    }
    .right-column {
      flex: 1;
      height: 100%;
      box-sizing: border-box;
      overflow: scroll;
      background: #f5f6f8;
      position: relative;
      .category {
        margin-bottom: 6px;
        background: #fff;
        &:last-child {
          margin-bottom: 0;
        }
        .first-title {
          display: flex;
          flex-direction: column;
          justify-content: center;
          padding: 8px 0 8px 20px;
          position: sticky;
          top: -1px;
          left: 0;
          width: 100%;
          font-weight: bold;
          font-size: 22px;
          color: #222;
          background: #ffffff;
          z-index: 1;
          box-sizing: border-box;
        }
        .second-item {
          justify-content: space-between;
          font-family: PingFang-SC, PingFang-SC;
          font-size: 22px;
          color: #666;
          border-top: 1px solid #f5f5f5;
          .second-item-title {
            display: flex;
            align-items: center;
            padding: 14px 18px 14px 20px;
            .arrow-icon {
              width: 12px;
              height: 12px;
              transition: transform 0.3s linear;
            }
            .arrow-rotate {
              transform: rotate(180deg);
            }
            .second-item-title-text {
              display: flex;
              align-items: center;
              margin-right: 10px;
              margin-left: 8px;
              min-width: 0;
              .text-content {
                font-size: 22px;
                flex: 1;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
                min-width: 0;
              }
              .count-text {
                flex-shrink: 0;
                white-space: nowrap;
              }
            }
            .selected-img {
              margin-left: auto;
              width: 28px;
              height: 28px;
            }
          }
          .float-title {
            position: sticky;
            top: 24px;
            left: 0;
            background: #fff;
            box-shadow: 0px 1px 4px 0px rgba(228, 226, 226, 0.5);
          }
          .third-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 14px 17px 14px 38px;
            color: #7dacf3;
            background: #f7fbff;
            transition: all 0.3s ease;
            font-size: 22px;
            &:not(:last-child) {
              border-bottom: 1px solid #eaebec;
            }
            .selected-img {
              width: 28px;
              height: 28px;
            }
          }
          .third-item-special {
            font-weight: bold;
            padding: 8px 0 8px 38px;
            color: $primary-color;
            background: #f6f7f8;
            transition: all 0.3s ease;
            border-bottom: 1px solid #dee9f0;
          }
        }
      }
    }
  }

  .bottom-btn {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    padding: 12px;
    background: #ffffff;
    box-shadow: 0px -1px 4px 0px rgba(144, 167, 212, 0.5);
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    justify-content: center;
    gap: 24px;
    z-index: 2;

    .left-btn,
    .right-btn {
      flex-shrink: 0;
      background: #f8f8f8;
      border-radius: 12px;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: bold;
      font-size: 24px;
      color: #999999;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      width: 296px;
      padding: 10px 0;
    }

    .left-btn {
      background: #f8f8f8;
      border: 1px solid #f8f8f8;
      &.active {
        border: 1px solid $primary-color;
        color: $primary-color;
      }
    }
    .right-btn {
      color: #ffffff;
      background: $primary-color;
    }
  }
}
</style>
